<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8">
		<title>jQuery datePicker demo: limit available dates with ajax</title>
		
		<!-- firebug lite -->
		<script type="text/javascript" src="firebug/firebug.js"></script>

        <!-- jQuery -->
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
        
        <!-- required plugins -->
		<script type="text/javascript" src="scripts/date.js"></script>
		<!--[if IE]><script type="text/javascript" src="scripts/jquery.bgiframe.min.js"></script><![endif]-->
        
        <!-- jquery.datePicker.js -->
		<script type="text/javascript" src="scripts/jquery.datePicker.js"></script>
        
        <!-- datePicker required styles -->
		<link rel="stylesheet" type="text/css" media="screen" href="styles/datePicker.css">
		
        <!-- page specific styles -->
		<link rel="stylesheet" type="text/css" media="screen" href="styles/demo.css">
        
        <!-- page specific scripts -->
		<script type="text/javascript" charset="utf-8">
            $(function()
            {
				
				var allowedDay;
				var numNights;

				var tomorrow = new Date().addDays(1);
				
				// add a listener for the form submit for this demo to illustrate that the date field on the form is being sucessfully set
				$('#chooseDateForm').bind(
					'submit',
					function()
					{
						var v = $datePicker.val();
						alert(v == '' ? 'You didn\'t select a date' : 'You selected ' + v);
						return false;
					}
				);

				
				$('#fill-button').bind(
					'click',
					function()
					{
						$.get('datePickerLimitAvailableDatesAjaxToLoad.txt', onDataLoaded);
						return false;
					}
				);

				function onDataLoaded(data)
				{

					$fillmewithajax = $('#fillmewithajax');

					$fillmewithajax.html(data);
				
					$durationRules = $('#durationRules', $fillmewithajax);
					$datePicker = $('#datePicker', $fillmewithajax);
					$datePicker.datePicker(
						{
							startDate: tomorrow.asString(),
							renderCallback:function ($td, thisDate, month, year)
							{
								var alreadyDisabled = $td.is('.disabled');
								if (allowedDay && !isNaN(allowedDay) && thisDate.getDay() != allowedDay && !alreadyDisabled) {
									// the disabled class prevents the user from being able to select the element.
									// the disallowed-day class provides a hook for different CSS styling of cells which are disabled 
									// by this rule vs cells which are disabled because e.g. they fall outside the startDate - endDate range.
									$td.addClass('disabled disallowed-day');
								} else if (!alreadyDisabled) {	// only add the highlight class if the date wasn't already for some 
																// reason disabled (e.g. it is outside the startDate - endDate range)
									$td.addClass('highlight');
									
									// we also want to highlight the other related days when you roll over the relevant date
									var $allTDs = $('td', $td.parent().parent());
									var td = $td[0];

									for (var i=0; i<$allTDs.length; i++) {
										if ($allTDs[i] == td) {
											break;
										}
									}
									var includedNightCells = [];
									for (var j=i; j<i+numNights; j++) {
										includedNightCells.push($allTDs[j]);
									}
									var $includedNightCells = $(includedNightCells)	;

									$td.hover(
										function()
										{
											$includedNightCells.addClass('included-night');
										},
										function()
										{
											$allTDs.removeClass('included-night');
										}
									);
								}
							}
						}
					).bind(
						'dpDisplayed',
						function(event, datePickerDiv)
						{
							var selectedOption = $('option[value=' + $durationRules.val() + ']', $durationRules);
							var message = selectedOption.attr('rel');
							if (message)
							{
								$(datePickerDiv).append('<div id="datepicker-message">' + message + '</div>')
							}
						}
					);

					$durationRules.bind(
						'change', 
						function()
						{
							var rules = $durationRules.val().split(',');
							numNights = parseInt(rules[0]);
							allowedDay = parseInt(rules[1]);

							var currentSelectedDate = Date.fromString($datePicker.val());
							if (currentSelectedDate.getTime() < tomorrow.getTime())
							{
								currentSelectedDate = Date.fromString(tomorrow.asString());
							}

							// if the current selected date is illegal via the new rules then keep incrementing to the next acceptable date...
							while (allowedDay && currentSelectedDate.getDay() != allowedDay) {
								currentSelectedDate.addDays(1);
							}
							$datePicker.dpSetSelected(currentSelectedDate.asString(), true, true);
						}
					).trigger('change');
				}
            });
		</script>

		<style type="text/css">
			table.jCalendar td
			{
				border: 1px solid;
				padding: 3px 4px;
			}
			table.jCalendar td.disabled,
			table.jCalendar td.disabled.dp-hover
			{
				background: #ccc;
				border: 1px solid #ccc;
				color: #000;
			}
			table.jCalendar td.disabled.other-month,
			table.jCalendar td.disabled.other-month.dp-hover
			{
				border: 1px solid #eee;
			}
			table.jCalendar td.highlight,
			table.jCalendar td.other-month.highlight
			{
				background: #dd6;
				color: #000;
				border: 1px solid #dd6;
			}
			table.jCalendar td.highlight.dp-hover
			{
				background: #ee0;
				border: 1px solid #000;
			}
			table.jCalendar td.selected,
			table.jCalendar td.selected.other-month,
			table.jCalendar td.selected.dp-hover
			{
				background: #ff0;
				color: #000;
				border: 1px solid #000;
			}
			table.jCalendar td.included-night,
			table.jCalendar td.other-month.included-night
			{
				border: 1px solid #ee0; 
				background: #ee0;
			}

			div#datepicker-message
			{
				text-align: center;
				padding: 2px;
			}

			div.step
			{
				overflow: hidden;
			}
		</style>
		
	</head>
	<body>
        <div id="container">
            <h1>jQuery datePicker demo: limit available dates with ajax</h1>
			<p><a href="index.html">&lt; date picker home</a></p>
            <p>
                The following example demonstrates how you can limit the available dates for clicking on the calendar based
				on the values in a dropdown.
            </p>
			<p>
				It also demonstrates how you can add behaviour to the date picker so that when a date is rolled over the following
				X days are also highlighted.
			</p>
			<p>
				This version is adapted very slightly from the <a href="datePickerLimitAvailableDates.html">original version</a> because
				it demonstrates how you can load the date picker in via ajax and then instantiate it...
			</p>
			<form name="chooseDateForm" id="chooseDateForm" action="#">
				<div id="fillmewithajax">
					Click <a href="noJS.html" id="fill-button">here</a> to load the form and instantiate the behaviours...
				</div>
			</form>
			<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi turpis augue, mollis sit amet, tempus eu, hendrerit a, lorem. Nullam eget enim quis orci mollis facilisis. Mauris nisi neque, dictum ut, convallis aliquam, fringilla at, libero. Pellentesque tempor velit sit amet odio. Proin consectetur odio eu neque. Nullam est. Praesent purus sem, viverra id, pharetra id, elementum quis, leo. Vestibulum et sem. Ut interdum. Donec commodo ligula sit amet odio. Cras nulla erat, cursus at, mollis non, dapibus faucibus, quam. Curabitur lectus justo, tempus sed, mattis quis, lobortis non, urna.</p>

			<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultrices urna eu mi. Praesent eleifend, justo at mollis vestibulum, risus mi elementum quam, ut bibendum metus tellus id eros. Morbi consequat interdum nisi. In semper nisi vel risus. Nam purus purus, lobortis ut, pulvinar vel, egestas in, nisl. Duis auctor erat in risus. Cras a nisi. Nullam viverra, augue quis adipiscing pulvinar, nisi ante tincidunt nunc, eget placerat lacus mauris in odio. Sed eu justo eget orci consectetur interdum. Phasellus condimentum aliquam quam. Pellentesque sit amet ante pretium pede commodo porttitor. Pellentesque in nunc sagittis nunc pellentesque ullamcorper. Morbi ligula. Pellentesque non purus a neque porttitor aliquam. Curabitur a urna. Phasellus scelerisque, massa non sagittis varius, neque risus venenatis turpis, vitae accumsan neque sapien et elit. Sed ornare venenatis risus.</p>

			<p>In eget ligula nec lorem lobortis auctor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque felis massa, facilisis sit amet, cursus sed, bibendum quis, sem. Aenean facilisis nisi. Nulla pede eros, hendrerit eget, mollis aliquam, aliquet vitae, augue. Fusce vehicula. Etiam aliquam nulla eu orci. Etiam lorem. Nulla at lectus et tortor commodo lacinia. In a nulla.</p>

			<p>Nulla sed tellus. Cras in mi eu est congue eleifend. Duis a justo. Aliquam erat volutpat. Cras interdum, risus eget ullamcorper iaculis, lorem orci aliquet sapien, id ullamcorper ligula diam volutpat purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In vel libero non tellus vehicula congue. In varius nisl vitae sem. Morbi risus. Sed erat metus, egestas ac, suscipit ut, accumsan ut, lorem. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla odio dui, suscipit ac, gravida et, dignissim dapibus, nunc. Aenean sollicitudin nibh sit amet elit.</p>

			<p>Proin in risus. Morbi fermentum molestie metus. Donec sed purus. Aliquam pellentesque semper dui. Sed mollis accumsan diam. Cras dictum, dolor ac ullamcorper varius, arcu sapien luctus lectus, vel semper massa mi in massa. Nam mi metus, rhoncus vel, pretium vel, tempus nec, purus. Nullam vel massa. Ut urna. Pellentesque lectus enim, ultricies a, feugiat at, fringilla id, nisl. Aliquam nibh ante, porta in, facilisis auctor, eleifend vitae, erat. Nam lorem. Quisque eget elit malesuada ligula vulputate ultrices. Aliquam erat volutpat. Vivamus ornare aliquam urna. </p>
		</div>
	</body>
</html>